package com.qifan.energy.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import com.orhanobut.logger.Logger;
import com.qifan.energy.bean.vo.GenerateOrderParamVO;
import com.qifan.energy.global.Keys;
import com.qifan.energy.global.Values;
import com.qifan.energy.BuildConfig;
import com.qifan.energy.R;
import com.qifan.energy.http.net.NetUtils;
import com.qifan.energy.http.response.MyObserver;
import com.qifan.energy.util.ActivityStackUtil;
import com.qifan.energy.util.SharedPreferencesUtil;
import com.qifan.energy.util.ToastUtils;
import com.qifan.energy.util.eventbus.EventBusUtils;
import com.qifan.energy.util.eventbus.EventCode;
import com.qifan.energy.util.eventbus.EventMessage;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler{

	private static String TAG = "MicroMsg.WXEntryActivity";

	private IWXAPI api;
	private boolean isPayResponse = false;//判断是否收到响应

	/*private MyHandler handler;
	private static class MyHandler extends Handler {

		private final WeakReference<WXPayEntryActivity> wxEntryActivityWeakReference;

		public MyHandler(WXPayEntryActivity wxEntryActivity){
			wxEntryActivityWeakReference = new WeakReference<WXPayEntryActivity>(wxEntryActivity);
		}

		@Override
		public void handleMessage(Message msg) {
			int tag = msg.what;
			switch (tag) {
				case 1: {
					Bundle data = msg.getData();
					JSONObject json = null;
					try {
						json = new JSONObject(data.getString("result"));
						String openId, accessToken, refreshToken, scope;
						openId = json.getString("openid");
						accessToken = json.getString("access_token");
						refreshToken = json.getString("refresh_token");
						scope = json.getString("scope");
						ToastUtils.showShort(openId + accessToken + refreshToken + scope);
						*//*Intent intent = new Intent(wxEntryActivityWeakReference.get(), SendToWXActivity.class);
						intent.putExtra("openId", openId);
						intent.putExtra("accessToken", accessToken);
						intent.putExtra("refreshToken", refreshToken);
						intent.putExtra("scope", scope);
						wxEntryActivityWeakReference.get().startActivity(intent);*//*
					} catch (JSONException e) {
						Log.e(TAG, e.getMessage());
					}
				}
			}
		}
	}*/

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		/*handler = new MyHandler(this);*/
		api = WXAPIFactory.createWXAPI(this, BuildConfig.WX_APPKEY,true);
		api.registerApp(BuildConfig.WX_APPKEY);
		try {
			api.handleIntent(getIntent(), this);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		setIntent(intent);
		api.handleIntent(intent, this);
	}

	/**
	 * 处理请求回调
	 * @param req
	 */
	@Override
	public void onReq(BaseReq req) {
		switch (req.getType()) {
			case ConstantsAPI.COMMAND_PAY_BY_WX:
				ToastUtils.showShort("COMMAND_PAY_BY_WX");
				break;
			default:
				break;
		}
		finish();
	}

	/**
	 * 处理结果回调
	 * @param resp
	 */
	@Override
	public void onResp(BaseResp resp) {
		//收到响应
		isPayResponse = true;
		int result = 0;
		switch (resp.errCode) {
			case BaseResp.ErrCode.ERR_OK://支付成功
				result = R.string.errcode_success;
				int order_id = SharedPreferencesUtil.getData(Keys.ORDER_ID_KEY,0);
				GenerateOrderParamVO orderParamVO = new GenerateOrderParamVO();
            	orderParamVO.setOrderId(order_id);
            	orderParamVO.setPayType(Values.PayType.WEIXIN);
            	paySuccess(orderParamVO);
				break;
			case BaseResp.ErrCode.ERR_COMM://支付错误
				result = R.string.errcode_error;
				break;
			case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
				result = R.string.errcode_cancel;
				//通知刷新购物车
				EventBusUtils.post(new EventMessage<>(EventCode.EVENT_1, "EventData"));
				//提示并跳转
				ToastUtils.showShort("取消成功！");
				finish();
				ActivityStackUtil.finishTopActivity();
				finish();
				break;
			case BaseResp.ErrCode.ERR_AUTH_DENIED:
				result = R.string.errcode_deny;
				finish();
				break;
			case BaseResp.ErrCode.ERR_UNSUPPORT:
				result = R.string.errcode_unsupported;
				finish();
				break;
			default:
				result = R.string.errcode_unknown;
				finish();
				break;
		}

		/*ToastUtils.showShort(getString(result) + ", type=" + resp.getType());

		if (resp.getType() == ConstantsAPI.COMMAND_SUBSCRIBE_MESSAGE) {
			SubscribeMessage.Resp subscribeMsgResp = (SubscribeMessage.Resp) resp;
			String text = String.format("openid=%s\ntemplate_id=%s\nscene=%d\naction=%s\nreserved=%s",
					subscribeMsgResp.openId, subscribeMsgResp.templateID, subscribeMsgResp.scene, subscribeMsgResp.action, subscribeMsgResp.reserved);
			ToastUtils.showShort(text);
		}

		if (resp.getType() == ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM) {
			WXLaunchMiniProgram.Resp launchMiniProgramResp = (WXLaunchMiniProgram.Resp) resp;
			String text = String.format("openid=%s\nextMsg=%s\nerrStr=%s",
					launchMiniProgramResp.openId, launchMiniProgramResp.extMsg,launchMiniProgramResp.errStr);
			ToastUtils.showShort(text);
		}

		if (resp.getType() == ConstantsAPI.COMMAND_OPEN_BUSINESS_VIEW) {
			WXOpenBusinessView.Resp launchMiniProgramResp = (WXOpenBusinessView.Resp) resp;
			String text = String.format("openid=%s\nextMsg=%s\nerrStr=%s\nbusinessType=%s",
					launchMiniProgramResp.openId, launchMiniProgramResp.extMsg,launchMiniProgramResp.errStr,launchMiniProgramResp.businessType);
			ToastUtils.showShort(text);
		}

		if (resp.getType() == ConstantsAPI.COMMAND_OPEN_BUSINESS_WEBVIEW) {
			WXOpenBusinessWebview.Resp response = (WXOpenBusinessWebview.Resp) resp;
			String text = String.format("businessType=%d\nresultInfo=%s\nret=%d",response.businessType,response.resultInfo,response.errCode);
			ToastUtils.showShort(text);
		}

		if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
			SendAuth.Resp authResp = (SendAuth.Resp)resp;
			final String code = authResp.code;
			NetworkUtil.sendWxAPI(handler, String.format("https://api.weixin.qq.com/sns/oauth2/access_token?" +
							"appid=%s&secret=%s&code=%s&grant_type=authorization_code", "wxd930ea5d5a258f4f",
					"1d6d1d57a3dd063b36d917bc0b44d964", code), 1);
		}*/
	}

	/* 支付完成回调接口 */
	private void paySuccess(final GenerateOrderParamVO orderParamVO){
		NetUtils.orderPaySuccess(orderParamVO, new MyObserver<String>(this) {
			@Override
			public void onSuccess(String result) {
				//通知刷新购物车
				EventBusUtils.post(new EventMessage(EventCode.EVENT_1, "EventData"));
				EventBusUtils.post(new EventMessage(Keys.NOTIFY_EVENT.PAYSUCCESS,"paysuccess"));
				//提示并跳转
				ToastUtils.showShort("支付成功！");
				finish();
				ActivityStackUtil.finishTopActivity();
			}

			@Override
			public void onFailure(Throwable e, String errorMsg) {
				//ToastUtils.showShort(errorMsg);
				paySuccess2(orderParamVO);
			}
		});
	}

	private void paySuccess2(final GenerateOrderParamVO orderParamVO){
		NetUtils.orderPaySuccess(orderParamVO, new MyObserver<String>(this) {
			@Override
			public void onSuccess(String result) {
				//通知刷新购物车
				EventBusUtils.post(new EventMessage<>(EventCode.EVENT_1, "EventData"));
				//提示并跳转
				ToastUtils.showShort("支付成功！");
				finish();
				ActivityStackUtil.finishTopActivity();
			}

			@Override
			public void onFailure(Throwable e, String errorMsg) {
				ToastUtils.showShort(errorMsg);
				paySuccess3(orderParamVO);
			}
		});
	}

	private void paySuccess3(final GenerateOrderParamVO orderParamVO){
		NetUtils.orderPaySuccess(orderParamVO, new MyObserver<String>(this) {
			@Override
			public void onSuccess(String result) {
				//通知刷新购物车
				EventBusUtils.post(new EventMessage<>(EventCode.EVENT_1, "EventData"));
				//提示并跳转
				ToastUtils.showShort("支付成功！");
				finish();
				ActivityStackUtil.finishTopActivity();
			}

			@Override
			public void onFailure(Throwable e, String errorMsg) {
				ToastUtils.showShort("支付失败，请主动联系客服!");
			}
		});
	}

	@Override
	protected void onDestroy() {

		if (!isPayResponse) {
			Logger.i("isPayResponse : 成功");
			int order_id = SharedPreferencesUtil.getData(Keys.ORDER_ID_KEY,0);
			GenerateOrderParamVO orderParamVO = new GenerateOrderParamVO();
			orderParamVO.setOrderId(order_id);
			orderParamVO.setPayType(Values.PayType.WEIXIN);
			paySuccess(orderParamVO);
		} else {
			Logger.i("isPayResponse : 取消");
		}

		super.onDestroy();
	}
}